package com.example.demo.java8.stream;
import com.example.demo.entity.Employee;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *  @ author  zengqingfa
 *  @ created in    2020/2/23  13:58
 *
 */
public class StreamApiTest4 {

    //匹配与查找

    @Test
    public void test1() {
        List<Employee> employees = Employee.getEmployees();
        //检查是否匹配所有元素
        boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18);
        System.out.println(allMatch);

        //至少匹配一个元素
        boolean anyMatch = employees.stream().anyMatch(e -> e.getName().contains("雷"));
        System.out.println(anyMatch);

        //是否没有匹配的元素
        boolean noneMatch = employees.stream().noneMatch(e -> e.getName().contains("雷"));
        System.out.println(noneMatch);

        //第一个
        Optional<Employee> first = employees.stream().findFirst();
        System.out.println(first);

        //返回任意
        Optional<Employee> any = employees.stream().findAny();
        System.out.println(any);

        //数量
        long count = employees.stream().count();
        System.out.println(count);

        //最大值
        Optional<Employee> max = employees.stream().max((e1, e2) -> Integer.compare(e1.getAge(), e2.getAge()));
        System.out.println(max.get());

        //最小值
        Optional<Employee> min = employees.stream().min((e1, e2) -> Integer.compare(e1.getAge(), e2.getAge()));
        System.out.println(min.get());

        //内部迭代
        employees.stream().forEach(System.out::println);
    }


    //规约
    @Test
    public void testReduce() {
        //reduce(T identity,BinaryOperator)—可以将流中元素反复结合起来得到一个值，返回T
        // reduce(BinaryOpreator)----可以将流中元素反复结合起来，返回Optional< T >
        List<Integer> list = Arrays.asList(1, 3, 2, 6, 8, 3, 9);
        Integer reduce = list.stream().reduce(10, (x, y) -> x + y);
        Optional<Integer> sum = list.stream().reduce(Integer::sum);
        System.out.println(reduce);
        System.out.println(sum);
    }

    //收集 collect----将流转换为其他形式，接收一个Collector接口的实现，用于给Stream中元素做汇总的方法
    @Test
    public void testFilter() {
        //查询年龄大于45的员工，返回list或者set
        List<Employee> employees = Employee.getEmployees();
        List<Employee> employeeList = employees.stream().filter(e -> e.getAge() > 45).collect(Collectors.toList());
        Set<Employee> employeeSet = employees.stream().filter(e -> e.getAge() > 45).collect(Collectors.toSet());
       employeeList.forEach(System.out::println);
       employeeSet.forEach(System.out::println);

    }


}
